package com.photoeditor.demo.ui.activity.subscribe;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.billing.base.SkuWithType;
import com.billing.base.internal.SkuDetailsCacheManager;
import com.common.base.ComponentContext;
import com.common.base.ui.widget.ripple.RippleTextView;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.widget.FingerTouchButton;
import com.photoeditor.demo.util.AndroidDevice;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.photoeditor.demo.app.Global.PRIVACY_URL;
import static com.photoeditor.demo.app.Global.REFUND_URL;
import static com.photoeditor.demo.model.subscribe.manager.SkuManager.TYPE_MONTHLY;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_ACTION_SUCC;
import static com.photoeditor.demo.statistics.StatisticsConstant.EVENT_RETAIN_SUCCESS;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_ENTRANCE;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_MAIN_PAGE_TYPE;
import static com.photoeditor.demo.statistics.StatisticsConstant.KEY_SUB_PACK;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_A;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_B;
import static com.photoeditor.demo.statistics.StatisticsConstant.VALUE_SUB_PACK_MONTH;
import static com.photoeditor.demo.statistics.StatisticsConstant.VALUE_SUB_PACK_YEAR;
import static com.photoeditor.demo.util.CheckPhoneHasBottomBarUtils.hasNavBar;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextView;

public class SubscribeRetainDialogAActivity extends BaseSubscribeActivity {

    @Bind(R.id.btn_vip_confirm)
    FingerTouchButton mUserBButton;
    @Bind(R.id.tv_vip_dialog_tip)
    TextView mTvTip;
    @Bind(R.id.gender_swap)
    TextView genderSwap;
    @Bind(R.id.face_aging)
    TextView faceAging;
    @Bind(R.id.past_life)
    TextView pastLife;
    @Bind(R.id.cartoon_effect)
    TextView cartoonEffect;
    @Bind(R.id.beauty)
    TextView beauty;
    @Bind(R.id.powerful_editor)
    TextView powerfulEditor;
    private int mSkuType;
    private String mFreeDaysYearly;
    private String mPrice;
    private String mStatisticPage;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_subscribe_retain_dialog_a;
    }

    @Override
    protected void initView() {
        measureTextView(this,faceAging,68,86);
        measureTextView(this,genderSwap,68,86);
        measureTextView(this,pastLife,68,86);
        measureTextView(this,cartoonEffect,68,86);
        measureTextView(this,beauty,68,86);
        measureTextView(this,powerfulEditor,68,86);

        mStatisticPage = StatisticsConstant.EVENT_RETAIN;
    }

    //    @Override
//    protected void initView() {
//        TextView tvPrivacy = findViewById(R.id.tv_vip_privacy);
////        if (BuyUserManager.getInstance().isBuyUser()) {
////            tvPrivacy.setVisibility(View.GONE);
////        } else {
//        String privacyFull = getString(R.string.vip_privacy) + " | " + getString(R.string.vip_cancel_refund);
//        String privacy = getString(R.string.vip_privacy);
//        int privacySIndex = privacyFull.indexOf(privacy);
//        int privacyEIndex = privacySIndex + privacy.length();
//        String refund = getString(R.string.vip_cancel_refund);
//        int refundSIndex = privacyFull.indexOf(refund);
//        int refundEIndex = refundSIndex + refund.length();
//        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
//        builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
//            }
//        }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new UnderlineSpan(), refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                AndroidDevice.startWebView(ComponentContext.getContext(), REFUND_URL);
//            }
//        }, refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        tvPrivacy.setHighlightColor(getResources().getColor(R.color.transparent));
//        tvPrivacy.setLinkTextColor(tvPrivacy.getCurrentTextColor());
//        tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
//        tvPrivacy.setText(builder);
//        mStatisticPage = StatisticsConstant.EVENT_RETAIN;
//
//    }

    private void initPriceView() {
        //拿不到策略时，默认展示年费
        int hasPrice = R.string.vip_year_tip;
        if (mSkuType == TYPE_MONTHLY) {
            hasPrice = R.string.vip_month_tip;
        }
        mTvTip.setText(String.format(getResources().getString(hasPrice), mPrice));
    }

    @Override
    protected void initData() {
        super.initData();
        mSkuType = SVipStrategyManager.getInstance().getFirstSubscribeType();

        mFreeDaysYearly = SkuManager.getVipFreeDays(mSkuType);
        String skuYear = SkuManager.getSkuInfoLast(mSkuType);
        if (mSkuType == TYPE_MONTHLY) {
            mPrice = SkuManager.getVipPriceBMonth();
        } else {
            mPrice = SkuManager.getVipPriceBYear();
        }
        if (!TextUtils.isEmpty(skuYear)) {
            SkuWithType skuWithType = new SkuWithType(skuYear, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType);
            if (cacheSkuDetails != null) {
                if (mSkuType == SkuManager.TYPE_YEARLY) {
                    BigDecimal b1 = new BigDecimal(Float.toString(cacheSkuDetails.getPriceAmountMicros() / 1000000.0f));
                    BigDecimal b2 = new BigDecimal(12);
                    BigDecimal divide = b1.divide(b2, 2, RoundingMode.DOWN);
                    mPrice = cacheSkuDetails.getPriceCurrencyCode() + " " + b1;
                } else if (mSkuType == TYPE_MONTHLY) {
                    mPrice = cacheSkuDetails.getPrice();
                }
            }
        }
        initPriceView();
    }

    @Override
    protected boolean isPurchaseSuccess(List<Purchase> purchases) {
        boolean mIsYearlyVip = false;
        if (purchases != null) {
            for (Purchase purchase : purchases) {
                String sku;
                if (purchase != null && (sku = purchase.getSku()) != null) {
                    String[] yearlySkus = SkuManager.getSkuInfo(mSkuType);
                    for (String yearlySku : yearlySkus) {
                        if (TextUtils.equals(sku, yearlySku)) {
                            mIsYearlyVip = true;
                        }
                    }
                }
            }
        }

        return mIsYearlyVip;
    }

    @Override
    protected void onPurchaseSuccess() {
        //测试
        StatisticsUtils.statisticGrowingIo(EVENT_RETAIN_SUCCESS,
                KEY_SUB_PACK, (mSkuType==TYPE_MONTHLY) ? VALUE_SUB_PACK_MONTH: VALUE_SUB_PACK_YEAR,
                KEY_MAIN_PAGE_TYPE, type,
                StatisticsConstant.KEY_SKU,sku);

    }

    public static void startActivity(Activity activity, String entrance, int resultcode, SVipController.OnSubscribeCloseListener listener) {
        Intent intent = new Intent(activity, SubscribeRetainDialogAActivity.class);
        intent.putExtra(EXTRA_TYPE,"A");
        intent.putExtra(EXTRA_IS_RETAIN,true);
        activity.startActivityForResult(intent, resultcode);
        sOnSubscribeCloseListener = listener;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(hasNavBar(this)){//有虚拟键
            hideBottomUIMenu();
        }
        if (mUserBButton != null) {
            mUserBButton.a();
        }
    }

    @Override
    public void onBackPressed() {
        onCloseClick();
    }

    @OnClick(R.id.iv_vip_close)
    void onCloseClick() {
        finish();
        statisticBack(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mUserBButton != null) {
            mUserBButton.cancel();
        }
    }

    @OnClick(R.id.btn_vip_confirm)
    void onActionClick() {
        String[] normalSkus = SkuManager.getSkuInfo(mSkuType);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        String clickStatistic;
        if (mSkuType == TYPE_MONTHLY) {
            clickStatistic = StatisticsConstant.SUB_PACK_VALUE_MONTHLY;
            int subscribeType = SVipStrategyManager.getInstance().getFirstSubscribeType();
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_CLICK,
//                    StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_MONTH,
//                    StatisticsConstant.KEY_AB_TYPE, StatisticsConstant.VALUE_A);
        } else {
            clickStatistic = StatisticsConstant.SUB_PACK_VALUE_ANNUAL;
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RETAIN_CLICK,
//                    StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_YEAR,
//                    StatisticsConstant.KEY_AB_TYPE, StatisticsConstant.VALUE_A);
        }
        subscribe(normalSkus[normalSkus.length - 1],
                clickStatistic);
    }

    @Override
    public void finish() {
        setResult(RESULT_OK);
        super.finish();
        overridePendingTransition(R.anim.activity_no_animation, R.anim.activity_no_animation);
    }

    @Override
    public String getStatisticPageStr() {
        return mStatisticPage;
    }

    @Override
    public String getSubscribeTypeStr() {
        return MAIN_PAGE_TYPE_A;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}
